package com.example.demo.controller.admin;

import com.example.demo.Util.Result;
import com.example.demo.Util.ResultUtil;
import com.example.demo.mapper.MaterialMap;
import com.example.demo.po.Material;
import com.example.demo.po.News;
import com.example.demo.service.MaterialService;
import com.example.demo.service.NewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/material")
public class MaterialController {

    @Autowired
    MaterialMap materialMap;

    @Autowired
    MaterialService materialService;

    @Autowired
    NewsService newsService;

    @PostMapping("save")
    public Result SaveMaterial(@RequestBody Material material){
        Result result = materialService.SaveMaterial(material);

        News news = new News();
          news.setTitle("新增"+material.getName());
          news.setContent("新增"+material.getName());
         news.setTime("");
        news.setType(0);
        newsService.SaveNews(news);

        return result;
    }

    @GetMapping("delete/{id}")
    public Result DeleteMaterial(@PathVariable int id){

        materialMap.DeleteMaterial(id);
        return ResultUtil.success("删除成功");
    }

    @PostMapping("/update")
    public Result UpdateMaterial(@RequestBody Material material){

        Result result = materialService.UpdateMaterial(material);
        return result;

    }

    @GetMapping("/get")
    public Result GetMaterials(@RequestParam("type") int type){
        if(type == 3){
            return ResultUtil.success(materialMap.GetAllMaterials());

        }

        return ResultUtil.success(materialMap.GetMaterials(type));

    }
    @GetMapping("/search")
    public Result GetMaterialsByName(@RequestParam("name") String name,@RequestParam("type") int type){
        if(StringUtils.isEmpty(name)){
            return ResultUtil.success(materialMap.GetMaterials(type));
        }
        List<Material> collect = materialMap.GetMaterialsByName("%" + name + "%").stream().filter(i -> i.getType() == type).collect(Collectors.toList());
        return ResultUtil.success(collect);
    }

}
